﻿using LuaInterface;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Framework.UGUI
{
	public class UIDragListener : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
	{
		public static UIDragListener Get(GameObject go)
		{
			return go.OnceAddComponent<UIDragListener>();
		}

		public static UIDragListener GetWithPath(GameObject go, string path)
		{
			var targetTransform = go.transform.Find(path);
			if (targetTransform != null)
			{
				return Get(targetTransform.gameObject);
			}
			return null;
		}

		private GeneralCallBackWithParam _dragCallback;
		private GeneralCallBackWithParam _dragBeginCallback;
		private GeneralCallBackWithParam _dragEndCallback;

		public void AddDragListener(LuaFunction luaDrag, LuaTable luaTarget, object param = null)
		{
			GeneralCallBackWithParam.GetOrReuse(ref _dragCallback, luaDrag, luaTarget, param);
		}

		public void AddDragBeginListener(LuaFunction luaDragBegin, LuaTable luaTarget, object param = null)
		{
			GeneralCallBackWithParam.GetOrReuse(ref _dragBeginCallback, luaDragBegin, luaTarget, param);
		}

		public void AddDragEndListener(LuaFunction luaDragEnd, LuaTable luaTarget, object param = null)
		{
			GeneralCallBackWithParam.GetOrReuse(ref _dragEndCallback, luaDragEnd, luaTarget, param);
		}

		public void RemoveDragListener()
		{
			GeneralCallBackWithParam.RecycleInst(ref _dragCallback);
		}

		public void RemoveDragBeginListener()
		{
			GeneralCallBackWithParam.RecycleInst(ref _dragBeginCallback);
		}

		public void RemoveDragEndListener()
		{
			GeneralCallBackWithParam.RecycleInst(ref _dragEndCallback);
		}

		public void OnDrag(PointerEventData eventData)
		{
			if (null != _dragCallback)
			{
				GeneralCallBackWithParam.Invoke(ref _dragCallback, eventData);
			}
		}

		public void OnBeginDrag(PointerEventData eventData)
		{
			if (null != _dragBeginCallback)
			{
                GeneralCallBackWithParam.Invoke(ref _dragBeginCallback, eventData);
			}
		}

		public void OnEndDrag(PointerEventData eventData)
		{
			if (null != _dragEndCallback)
			{
                GeneralCallBackWithParam.Invoke(ref _dragEndCallback, eventData);
			}
		}

		void OnDestroy()
		{
			if (_dragCallback != null)
			{
				GeneralCallBackWithParam.RecycleInst(ref _dragCallback);
				UIEventDebugger.LogUIEventError("UIDragListener.drag", gameObject);
			}
			if (_dragBeginCallback != null)
			{
				GeneralCallBackWithParam.RecycleInst(ref _dragBeginCallback);
				UIEventDebugger.LogUIEventError("UIDragListener.dragBegin", gameObject);
			}
			if (_dragEndCallback != null)
			{
				GeneralCallBackWithParam.RecycleInst(ref _dragEndCallback);
				UIEventDebugger.LogUIEventError("UIDragListener.dragEnd", gameObject);
			}
		}
	}
}
